17. 列表和循环

🔣 列表和循环

在 Python 中, 列表 项放入方括号里,并用逗号分隔列表项。你从这节课的第一个示例就看到列表了,当时我们的 turtle 叫做 george ,并绘制出一个正方形:

for side in [1, 2, 3, 4]:
    george.forward(100)
    george.right(90)

此代码中的列表是 [1, 2, 3, 4] 。列表和 for 循环紧密合作。但在上述示例(以及我们到目前为止见过的所有示例)中,我们并没有实际使用列表中的数字,只是考虑到有四个列表项。

(是 four 循环,算押韵吧。)

但是,我们可以在 for 循环中的代码里使用列表中的数字。举个例子—

Task Description:

完成这些操作后,请选中它们—

Task List:

Task Feedback:

可以看出,这里的 turtle 使用列表中的长度判断每次循环运行时,要移动多远。

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: html-live
  • Opened files (when workspace is loaded): n/a

备注 :如果你无法打开上面的workspace,请去 这里

Python:遍历列表

下面是上述代码中的一行代码。

for length in lengths:

lengths 是什么?

SOLUTION: 包含数字列表的变量。

下面还是相同的代码行:

for length in lengths:

对于 length (没有 s ),哪些表述正确??

其中 两个 表述正确。请标记出这 两个 正确的表述:

SOLUTION:
  • 它也是一个变量,但是和 `lengths` 不同,它不包含完整的列表。
  • 每次循环运行时,`length` 变量都被分配 `lengths` 列表中的一个项目。